<?php defined('SYSPATH') or die('No direct script access.');

class Model_Image extends ORM {
    
    protected $_table_name = 'images';
    protected $_primary_key = 'id';

    const DIRECTORY_PATH = 'media/uploads/';
    
    protected $_belongs_to = array(
        'user' => array(
            'model' => 'User',
            'foreign_key' => 'user_id'
        )
    );
    
    public function rules() {
        return array(
            'name' => array(
                array('not_empty')
            )
        );
    }
    
    public static function upload($file){

        // Generate a random name
        $symbols = '0123456789abcdefghijklmnopqrstuvwxyz';

        $filename = substr(str_shuffle($symbols), 0, 16);

        $im = Image::factory($file);
        
        switch ($im->type)
        {
            case IMAGETYPE_JPEG:
                $ext = 'jpg';
            break;
            case IMAGETYPE_PNG:
                $ext = 'png';
            break;
            default:
                $ext = 'jpg';
        }

        // Resizing and image loading
        if($im->width > 150 AND $im->height > 200)
        {
            $im->resize(150, 200, Image::NONE);
        }
        $im->save(Model_Image::DIRECTORY_PATH."small_$filename.$ext");

        $im = Image::factory($file);
        $im->save(Model_Image::DIRECTORY_PATH."$filename.$ext");

        return "$filename.$ext";
    }

}